package com.rec.smile.controller;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.rec.smile.model.User;

@Controller
@RequestMapping
public class IndexController {
	//url:http://localhost:8082/helloworld
	@RequestMapping("/helloworld")
	public String redirct(){
		return "helloworld";
	}
	
	@RequestMapping("/p1")
	public String toUser(User user){
		System.out.println(user);
		return "helloworld";
	}
	
	@RequestMapping("/date/{id}")
	public String date(@PathVariable("id") Date date){
		System.out.println(date);
		return "helloworld";
	}
	
	@InitBinder
	public void initDateBinder(ServletRequestDataBinder binder){
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
	
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	public String upload(HttpServletRequest req) throws Exception{
		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
		MultipartFile file = mreq.getFile("file");
		String fileName = file.getOriginalFilename();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+"upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
		fos.write(file.getBytes());
		fos.flush();
		fos.close();
		
		return "helloworld";
	}
	
	@RequestMapping(value = "/user",method= {RequestMethod.GET,RequestMethod.POST}, produces="application/json" )
	@ResponseBody
	public User get(){
		User user = new User();
//		user.setBirthday(new Date());
		user.setId(100);
		user.setEmail("qq@qq.com");
		user.setName("wer");
		return user;
	}
}
